package com.example.springbootpro.controller.upload;

import com.example.springbootpro.result.Result;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/upload-file")
public class UploadFileController {
    private String uploadDir;
    @Resource
    private ResourceLoader resourceLoader;
    @PostConstruct
    public void init() throws IOException {
//         org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:");
//        File projectRoot = resource.getFile().getParentFile();
//
//         uploadDir = new File(projectRoot, "uploads").getAbsolutePath();
//
//         if (!new File(uploadDir).exists()) {
//            new File(uploadDir).mkdirs();
//        }
//        uploadDir = uploadDir.replace("\\target","");
//        System.out.println("文件上传目录: " + uploadDir); // 打印路径方便调试
        uploadDir = System.getProperty("user.dir");
    }

     @PostMapping(value = "/referral")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile multipartFile) {

//        在这个虚拟机 todo 保存这个内容
//        return  Result.success("131231312231312313131313.png");
         if (multipartFile == null || multipartFile.isEmpty()) {
            return Result.error("上传文件不能为空");
        }

        try {
            String originalFilename = multipartFile.getOriginalFilename();
            if (originalFilename == null || originalFilename.lastIndexOf(".") < 0) {
                return Result.error("无效的文件名");
            }
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));

            String datePath = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String fileName = StringUtils.stripFilenameExtension(originalFilename);
            String newFilename = datePath + "_" + fileName + "_"
                    + UUID.randomUUID().toString().replace("-", "").substring(0, 8)
                    + fileExtension;

            // 创建日期子目录
            Path dateDir = Paths.get(uploadDir, datePath);
            if (!Files.exists(dateDir)) {
                Files.createDirectories(dateDir);
            }

            // 保存文件
            Path destPath = dateDir.resolve(newFilename);
            multipartFile.transferTo(destPath.toFile());

             String relativePath = "uploads/" + datePath + "/" + newFilename;
            return Result.success(relativePath);

        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统错误: " + e.getMessage());
        }
    }


}